package com.tomcat.myapplication.util;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.widget.DatePicker;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class DateAlert extends Activity {

	Calendar calendar = Calendar.getInstance();
	DatePickerDialog datePickerDialog;
	private TextView tview;
	
	
	public DateAlert(Context context, TextView tview) {
		this.tview = tview;
		try {
			String dateText = tview.getText().toString();
			if (dateText != null && dateText.trim().length() > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
				calendar.setTime(sdf.parse(dateText));
			}
		} catch (Exception e) {
		}
		datePickerDialog = new DatePickerDialog(context, listener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
	}

	private OnDateSetListener listener = new OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			StringBuffer sb = new StringBuffer();
			sb.append(year + "-");
			sb.append((monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1) + "-" : (monthOfYear + 1) + "-");
			sb.append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth);


			if(tview != null) {
				tview.setText(sb.toString());
			}

			if(datePickerSetListener != null){
				datePickerSetListener.onDateSet(sb.toString());
			}
		}
	};

	private DatePickerSetListener datePickerSetListener;

	public void setDatePickerSetListener(DatePickerSetListener datePickerSetListener) {
		this.datePickerSetListener = datePickerSetListener;
	}

	public interface DatePickerSetListener{
		public void onDateSet(String date);
	}


	public void show(){
		datePickerDialog.show();

	}

	
	public boolean isShowing(){
		return datePickerDialog.isShowing();
	}
	
}
